<?php

namespace app\apiadmin\service\statics;

use DateTime;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Client;
use MongoDB\Collection;
use think\db\Mongo;
use think\facade\Db;

class MongoDbService
{

    private $_tableName = "";
    private $_database;

    private $_conn;
    private $_instance;
    public static function getInstance($tableName)
    {
        // if (self::$_instance == null) {
        //     self::$_instance = new MongoDbService($liveId);
        // }
        return new MongoDbService($tableName);
    }

    public function __construct($tableName)
    {
        $this->_tableName = $tableName;
        $this->_database = env('mongodb.database');
    }
    public static function getConnection()
    {
        return Db::connect('mongodb');
    }

    /** @return Mongo mongo */
    public static function getTable($_tableName)
    {
        return Db::connect('mongodb')->table($_tableName);
    }

    /** @return Client Client */
    public static function getMongoDBClient()
    {
        //$mongodb_host = env('mongodb.host');
        //$mongddb_port = env('mongodb.port');
        $mongodb_url = env("mongodb.url");
        $database = env('mongodb.database');
        $clietn = new Client(
            $mongodb_url
        );

        return $clietn;
    }

    /** @return Collection */
    public function getCollection()
    {
        $clietn = self::getMongoDBClient();
        return $clietn->selectDataBase($this->_database)->__get(($this->_tableName));
    }

    /**
     * @author: zwx
     * @Description:  本地时间转UTC时间格式
     * @param {*} $datetime  本地时间， 格式 Y-m-d H:i:s
     * @Date: 2024-06-11 11:24:41
     */
    public static function timeToUTC($datetime = '')
    {

        if (!$datetime) {
            $datetime = date('Y-m-d H:i:s', time());
        }

        return new UTCDateTime($datetime);

    }

    /**
     * @author: zwx
     * @Description: UTC时间转本地时间  加8小时
     * @param {*} $isoDate   UTC时间
     * @Date: 2024-06-11 11:25:22
     */
    public static function UTCToTime($isoDate)
    {

        $dateTime = $isoDate->toDateTime()->getTimestamp();

        // 输出结果
        $send_time2 = date('Y-m-d H:i:s', $dateTime);
        return $send_time2;
    }

}
